<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert :closable="false" title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_mar">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedCateValue"
            :options="goodsCateList"
            :props="cateCascaderProps"
            @change="cateValueChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- Tab参数标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleParamsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            :disabled="isBtnDisabled"
            size="mini"
            type="primary"
            @click="addDialogVisible=true"
          >添加参数</el-button>
          <!-- 动态参数表格区域 -->
          <el-table :data="manyParamsData" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  :key="item.i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  @close="delPropTag(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 文本输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            :disabled="isBtnDisabled"
            size="mini"
            type="primary"
            @click="addDialogVisible=true"
          >添加属性</el-button>
          <!-- 静态属性表格区域 -->
          <el-table :data="onlyParamsData" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  :key="item.i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  @close="delPropTag(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 文本输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit">修改</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="活动名称" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addNewParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      goodsCateList: [],
      //   被选中的商品分类数据
      selectedCateValue: [],
      //   级联框配置项
      cateCascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      //   tab标签被选中的项
      activeName: "many",
      // 动态参数的数据
      manyParamsData: [],
      // 静态属性的数据
      onlyParamsData: [],
      // 显示与隐藏对话框
      addDialogVisible: false,
      // 对话框表单数据对象
      addForm: {
        attr_name: ""
      },
      // 对话框表单验证规则
      addFormRules: {
        attr_name: [{ required: true, message: "请输入数据", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getGoodsCateList();
  },
  methods: {
    // 获取商品分类列表所有的数据
    async getGoodsCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类数据失败!");
      this.goodsCateList = res.data;
      //   console.log(this.goodsCateList);
    },
    // 级联框x选中项变化的事件
    async cateValueChange() {
      if (this.selectedCateValue.length !== 3) {
        this.selectedCateValue = [];
        this.$message.warning("只允许为第三级分类设置相关参数");
        // 清空动态数据,清空表格
        this.manyParamsData = [];
        this.onlyParamsData = [];
        return;
      }
      this.getParamsData();
    },
    // 监听tab栏点击事件
    handleParamsClick() {
      this.getParamsData();
      //   console.log(this.activeName);
    },
    // 获取表格中动态参数或静态属性数据
    async getParamsData() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      );
      if (res.meta.status !== 200) return this.$message.error("获取参数失败!");
      //在赋值前对数据进行改造 转为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
        item.inputVisible = false;
        item.inputValue = "";
      });
      // vue中应该先给对象挂载属性,然后渲染到页面,因为数据渲染到页面之前会有set attr拦截器,添加一个 setter 如果先渲染到页面再挂载到属性的话这个属性就相当于失效了
      if (this.activeName == "many") {
        this.manyParamsData = res.data;
      } else {
        this.onlyParamsData = res.data;
      }
    },
    // 对话框关闭
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加参数
    addNewParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        // 发送数据
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) return this.$message.error("添加失败!");
        this.$message.success("添加成功");
        this.getParamsData();
        this.addDialogVisible = false;
      });
    },
    // 表单跟按钮来回切换
    // 点击按钮触发显示表单
    showInput(row) {
      row.inputVisible = true;
      // 异步任务:等渲染完成后,再来让页面的input原生获取焦点
      this.$nextTick(_ => {
        //  el-input组件实例
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 键盘弹起或失去焦点
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      // 如果文本框内容不为空
      // 1.添加到数组中,
      row.attr_vals.push(row.inputValue);
      row.inputValue = "";
      row.inputVisible = false;
      // 2发起添加参数的网络请求
      this.putAttr(row);
    },
    // 删除参数功能
    delPropTag(i, row) {
      row.attr_vals.splice(i, 1);
      this.putAttr(row);
    },
    async putAttr(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(",")
        }
      );
      if (res.meta.status !== 200) return this.$message.error("更新参数失败");
      this.$message.success("更新参数成功!");
    }
  },
  computed: {
    isBtnDisabled() {
      if (this.selectedCateValue.length !== 3) {
        return true;
      } else {
        return false;
      }
    },
    // 分类id
    cateId() {
      if (this.selectedCateValue.length == 3) {
        return this.selectedCateValue[2];
      } else {
        return null;
      }
    },
    // 对话框标题
    titleText() {
      return this.activeName == "many" ? "动态参数" : "静态属性";
    }
  }
};
</script>
<style lang="less" scoped>
.cat_mar {
  margin: 15px 0;
}
.el-cascader {
  width: 300px;
}
.input-new-tag {
  width: 120px;
}
</style>
